import { HttpStatus, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateTagDto } from './dto/create-tag.dto';
import { UpdateTagDto } from './dto/update-tag.dto';
import { Tag } from './tags.entity';

@Injectable()
export class TagsService {
  constructor(
    @InjectRepository(Tag)
    private tagUserService: Repository<Tag>,
  ) {}

  // 创建标签
  async create(createTagDto: CreateTagDto) {
    const { tagName } = createTagDto;
    const isTagName = await this.tagUserService.findOne({ tagName });
    if (isTagName) {
      return {
        code: HttpStatus.INTERNAL_SERVER_ERROR,
        message: '标签名已存在！',
      };
    }
    return this.tagUserService
      .save(createTagDto)
      .then(() => {
        return {
          code: HttpStatus.OK,
          message: '创建标签成功！',
        };
      })
      .catch((error) => {
        return {
          code: HttpStatus.INTERNAL_SERVER_ERROR,
          message: error.message,
        };
      });
  }

  // 查询所有标签
  async findAll() {
    const data = await this.tagUserService.find();
    return {
      code: HttpStatus.OK,
      data,
    };
  }

  // 查询单个标签
  async findOne(id: number) {
    const data = await this.tagUserService.findOne(id);
    if (!data) {
      return {
        code: HttpStatus.INTERNAL_SERVER_ERROR,
        message: '标签不存在！',
      };
    }
    return {
      code: HttpStatus.OK,
      data,
    };
  }

  // 修改单个标签
  async update(id: number, updateTagDto: UpdateTagDto) {
    const tag = await this.tagUserService.findOne(id);
    if (!tag) {
      return {
        code: HttpStatus.INTERNAL_SERVER_ERROR,
        message: '标签不存在！',
      };
    }
    const { tagName } = updateTagDto;
    tag.tagName = tagName;
    return this.tagUserService
      .update(id, tag)
      .then(() => {
        return {
          code: HttpStatus.OK,
          message: '修改成功！',
        };
      })
      .catch((error) => {
        return {
          code: HttpStatus.INTERNAL_SERVER_ERROR,
          message: error.message,
        };
      });
  }

  // 删除单个标签
  async remove(id: number) {
    const tag = await this.tagUserService.findOne(id);
    if (!tag) {
      return {
        code: HttpStatus.INTERNAL_SERVER_ERROR,
        message: '标签不存在！',
      };
    }
    return this.tagUserService
      .remove(tag)
      .then(() => {
        return {
          code: HttpStatus.OK,
          message: '删除成功！',
        };
      })
      .catch((error) => {
        return {
          code: HttpStatus.INTERNAL_SERVER_ERROR,
          message: error.message,
        };
      });
  }
}
